#include<iostream>
#include<vector>
#include<unistd.h>
#include<cerrno>
#include<cstring>
#include<fcntl.h>
#include<cstdlib>

#include "tool.hpp"

//typedef void(*fun_t)(); 
//你可以参考一下库，所以这里不用写

int main()
{
    //测试非阻塞IO
    std::vector<fun_t> tasks;

    initTasks(tasks);

    //获取套接字
    int falgs = fcntl(0,F_GETFL); 
    //设置阻塞模式
    falgs |= O_NONBLOCK;
    int n = fcntl(0,F_SETFL,falgs);

    if(n == -1)
    {
        perror("fatal of fcntl");
        exit(-1);
    }


    while(true)
    {
        std::cout << "pelase cin#";
        fflush(stdout);

        char buffer[1024];
        ssize_t s = read(0, buffer, sizeof buffer-1);

        if(s > 0)
        {
            //buffer[s] = 0;
            buffer[s-1] = 0; //清除换行符  
            std::cout << buffer << std::endl;
        }
        else if(s == 0)
        {
            std::cout << "结束读取结束继续往后执行代码" << std::endl;
            exit(0);
        }
        else
        {

            if(errno == EAGAIN)
            {
                std::cout << "我不是异常了，我只是设置了非阻塞" << std::endl;
            }
            else if(errno == EINTR)
            {
                continue;
            }
            else{std::cout << strerror(errno) << std::endl; 
            exit(0);
            }
        }

        for(const auto& e : tasks)
        e();

        sleep(1);
    }
    return 0;
}